import { plugin, AMessage } from 'alemonjs'
import { command } from '../config/command'

import { exec } from 'child_process'
import { AppName } from '../app.config'

export class xianyu_update extends plugin {
  constructor() {
    super({
      dsc: '咸鱼插件更新',
      priority: 2000,
      rule: [...command.update]
    })
  }

  async update_plugin(e: AMessage) {
    exec(
      `git -C ./plugins/${AppName}/ pull --no-rebase`,
      (error: any, stdout: any, stderr: any) => {
        if (error) {
          console.error(`exec error: ${error}`)
          return
        } else {
          exec(
            `git -C ./plugins/${AppName}/ log -1 --pretty=format:"%cd %s"`,
            (error: { message: any }, stdout: string, stderr: any) => {
              if (error) {
                e.reply(`错误：${error.message}`)
                console.error(`exec error: ${error}`)
                return
              } else {
                const date = stdout.split(' ')[3]
                const message = stdout.split(' ').slice(4).join(' ')
                e.reply(`更新成功，重启生效\n${date} ${message}`)
                console.log(stdout)
              }
            }
          )
        }
      }
    )
  }
}
